﻿#include "MySQLDBHelper.h"

MySQLDBHelper::MySQLDBHelper()
{
	//第二次已有连接名，则使用就行
    if(QSqlDatabase::contains(this->driverName)){
        this->db=QSqlDatabase::database(this->driverName);
    }else {
    	// 没有指定连接名，则创建
        this->db = QSqlDatabase::addDatabase(this->driverName);
    }
	
	this->init();
    this->connect();
	//设置字符集为utf-8，以防乱码
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(codec);
    this->db.exec("set NAMES UTF8");
}

MySQLDBHelper::~MySQLDBHelper()
{
    this->db.close();
    QSqlDatabase::removeDatabase(this->driverName);
}

void MySQLDBHelper::init() {
	this->db.setHostName("127.0.0.1");
	this->db.setDatabaseName("qcwmpt");
	this->db.setUserName("root");
	this->db.setPassword("");
}

bool MySQLDBHelper::connect() {
    if (!this->db.open()) {
		QMessageBox::about(NULL, QObject::tr("MYSQL_ERROR"), this->db.lastError().text());
		return false;
	}
	else
    {
        this->query = (QSqlQuery)this->db;
        return true;
	}
}

QSqlQuery MySQLDBHelper::getQuery() {
	return this->query;
}
